package com.bestcem.xm.user.util.business;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 读取配置文件工具类
 *
 * @author Linked <zhijian.lin@idiaoyan.com>
 * @date 2022/3/3 13:50
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class FileUtils {

    public static final String INNER_USER_FILE_PATH = "/file/InnerUser.json";
    public static final String XLSX_SUFFIX = ".xlsx";
    public static final String XLSX_TYPE = "XLSX";

    /**
     * 读取json文件
     *
     * @param filePath
     * @return
     * @author liheng
     * @date 2021/5/19 14:52
     */
    public static Map<String, JSONArray> readInnerUserFile(String filePath) {
        ClassPathResource classPathResource = new ClassPathResource(filePath, FileUtils.class);
        File file = null;
        Map<String, JSONArray> keywordMap = new HashMap<>();
        try {
            file = classPathResource.getFile();
        } catch (IOException e) {
            if (log.isErrorEnabled()) {
                log.error("[user] read inner user file error! path:{}", filePath);
            }
            return keywordMap;
        }
        if (!file.isFile()) {
            if (log.isErrorEnabled()) {
                log.error("[user] read inner user file error! path:{}", filePath);
            }
            return keywordMap;
        }

        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            keywordMap = JSON.parseObject(fileInputStream, Map.class);
        } catch (IOException e) {
            if (log.isErrorEnabled()) {
                log.error("内部员工信息json出现异常，异常信息：", e);
            }
            return keywordMap;
        }
        return keywordMap;
    }

    /**
     * 删除文件
     *
     * @param file
     */
    public static void safeDelete(File file) {
        if (Objects.nonNull(file) && file.exists()) {
            try {
                Files.delete(file.toPath());
            } catch (Exception e) {
                log.error("文件删除出现异常", e);
            }
        }
    }
}
